// SettingsTypes.ts

// 基础设置类型定义
export interface BasicSettings {
  serverUrl: string;
  apiTimeout: number;
  enableLogging: boolean;
  debugMode: boolean;
  autoSaveInterval: number;
  cacheSize: number;
  notificationSound: boolean;
  lastUpdated?: string;
}

// 通知设置类型定义
export interface NotificationSettings {
  email: boolean;
  sms: boolean;
  push: boolean;
  courseUpdates: boolean;
  gradeUpdates: boolean;
  attendanceAlerts: boolean;
  systemMessages: boolean;
}

// 用户设置类型定义
export interface UserSettings {
  username: string;
  realName: string;
  email: string;
  role: string;
  avatar: string;
  notifications: NotificationSettings;
  permissions: string[];
  lastUpdated?: string;
}

// 主题类型定义
export type ThemeType = 'light' | 'dark' | 'system';

// 个性化设置类型定义
export interface PersonalizationSettings {
  theme: ThemeType;
  language: string;
  dateFormat: string;
  timeFormat: string;
  showNotifications: boolean;
  enableAnimation: boolean;
  lastUpdated?: string;
}

// 系统设置类型定义（包含所有设置）
export interface SystemSettings {
  basic: BasicSettings;
  user: UserSettings;
  personalization: PersonalizationSettings;
}

// 选项类型定义
export interface Option<T = string> {
  label: string;
  value: T;
}

// 主题选项
export const THEME_OPTIONS: Option<ThemeType>[] = [
  { label: '亮色', value: 'light' },
  { label: '暗色', value: 'dark' },
  { label: '跟随系统', value: 'system' }
];

// 语言选项
export const LANGUAGE_OPTIONS: Option[] = [
  { label: '简体中文', value: 'zh-CN' },
  { label: 'English (US)', value: 'en-US' },
  { label: '日语', value: 'ja-JP' },
  { label: '韩语', value: 'ko-KR' }
];

// 日期格式选项
export const DATE_FORMAT_OPTIONS: Option[] = [
  { label: 'YYYY-MM-DD (2023-12-25)', value: 'YYYY-MM-DD' },
  { label: 'MM/DD/YYYY (12/25/2023)', value: 'MM/DD/YYYY' },
  { label: 'DD/MM/YYYY (25/12/2023)', value: 'DD/MM/YYYY' },
  { label: 'YYYY年MM月DD日 (2023年12月25日)', value: 'YYYY年MM月DD日' }
];

// 时间格式选项
export const TIME_FORMAT_OPTIONS: Option[] = [
  { label: 'HH:mm:ss (24小时制)', value: 'HH:mm:ss' },
  { label: 'HH:mm (24小时制)', value: 'HH:mm' },
  { label: 'hh:mm:ss A (12小时制)', value: 'hh:mm:ss A' },
  { label: 'hh:mm A (12小时制)', value: 'hh:mm A' }
];

// 角色选项
export const ROLE_OPTIONS: Option[] = [
  { label: '管理员', value: 'admin' },
  { label: '教师', value: 'teacher' },
  { label: '学生', value: 'student' },
  { label: '家长', value: 'parent' }
];

// 权限选项
export const PERMISSION_OPTIONS: Option[] = [
  { label: '查看报告', value: 'viewReports' },
  { label: '管理用户', value: 'manageUsers' },
  { label: '管理课程', value: 'manageCourses' },
  { label: '发送消息', value: 'sendMessages' },
  { label: '系统设置', value: 'systemSettings' },
  { label: '数据导出', value: 'exportData' }
];

// 基础设置验证函数
export const validateBasicSettings = (settings: BasicSettings): { [key: string]: string } => {
  const errors: { [key: string]: string } = {};

  if (!settings.serverUrl.trim()) {
    errors.serverUrl = '服务器地址不能为空';
  } else {
    try {
      new URL(settings.serverUrl);
    } catch (e) {
      errors.serverUrl = '请输入有效的URL地址';
    }
  }

  if (!settings.apiTimeout || settings.apiTimeout <= 0) {
    errors.apiTimeout = 'API超时时间必须大于0';
  } else if (settings.apiTimeout > 300) {
    errors.apiTimeout = 'API超时时间不能超过300秒';
  }

  if (settings.autoSaveInterval < 0 || settings.autoSaveInterval > 300) {
    errors.autoSaveInterval = '自动保存间隔必须在0-300秒之间';
  }

  if (settings.cacheSize < 0 || settings.cacheSize > 4096) {
    errors.cacheSize = '缓存大小必须在0-4096MB之间';
  }

  return errors;
};

// 用户设置验证函数
export const validateUserSettings = (settings: UserSettings): { [key: string]: string } => {
  const errors: { [key: string]: string } = {};

  if (!settings.username.trim()) {
    errors.username = '用户名不能为空';
  } else if (settings.username.length < 3) {
    errors.username = '用户名至少需要3个字符';
  }

  if (!settings.realName.trim()) {
    errors.realName = '真实姓名不能为空';
  }

  if (!settings.email.trim()) {
    errors.email = '邮箱不能为空';
  } else {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(settings.email)) {
      errors.email = '请输入有效的邮箱地址';
    }
  }

  if (!settings.role) {
    errors.role = '请选择用户角色';
  }

  return errors;
};

// 个性化设置验证函数
export const validatePersonalizationSettings = (settings: PersonalizationSettings): { [key: string]: string } => {
  const errors: { [key: string]: string } = {};

  if (!settings.theme || !['light', 'dark', 'system'].includes(settings.theme)) {
    errors.theme = '请选择有效的主题模式';
  }

  if (!settings.language || !LANGUAGE_OPTIONS.some(option => option.value === settings.language)) {
    errors.language = '请选择有效的语言';
  }

  return errors;
};

// 默认基础设置生成函数
export const getDefaultBasicSettings = (): BasicSettings => ({
  serverUrl: 'https://api.example.com',
  apiTimeout: 30,
  enableLogging: true,
  debugMode: false,
  autoSaveInterval: 60,
  cacheSize: 1024,
  notificationSound: true
});

// 默认用户设置生成函数
export const getDefaultUserSettings = (): UserSettings => ({
  username: '',
  realName: '',
  email: '',
  role: 'student',
  avatar: '',
  notifications: {
    email: true,
    sms: false,
    push: true,
    courseUpdates: true,
    gradeUpdates: true,
    attendanceAlerts: true,
    systemMessages: true
  },
  permissions: ['viewReports']
});

// 默认个性化设置生成函数
export const getDefaultPersonalizationSettings = (): PersonalizationSettings => ({
  theme: 'system',
  language: 'zh-CN',
  dateFormat: 'YYYY-MM-DD',
  timeFormat: 'HH:mm',
  showNotifications: true,
  enableAnimation: true
});

// 默认系统设置生成函数
export const getDefaultSystemSettings = (): SystemSettings => ({
  basic: getDefaultBasicSettings(),
  user: getDefaultUserSettings(),
  personalization: getDefaultPersonalizationSettings()
});

// 从本地存储加载设置的工具函数
export function loadSettingsFromLocalStorage<T>(key: string, defaultValue: T): T {
  try {
    const storedValue = localStorage.getItem(key);
    if (storedValue) {
      return JSON.parse(storedValue) as T;
    }
  } catch (error) {
    console.error(`从本地存储加载设置失败 (${key}):`, error);
  }
  
  // 如果加载失败，保存默认值到本地存储
  try {
    localStorage.setItem(key, JSON.stringify(defaultValue));
  } catch (error) {
    console.error(`保存默认设置到本地存储失败 (${key}):`, error);
  }
  
  return defaultValue;
}

// 保存设置到本地存储的工具函数
export function saveSettingsToLocalStorage(key: string, settings: any): void {
  try {
    localStorage.setItem(key, JSON.stringify(settings));
  } catch (error) {
    console.error(`保存设置到本地存储失败 (${key}):`, error);
  }
}